<?php

namespace App\Services;

use App\Models\MailConfig;
use App\Models\SafeCenter;
use App\User;
use App\Models\UserProperty;
use App\Models\Money;
use common\utils\RedisKeys;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Request;
use common\utils\ValidateCode;
use common\utils\SysCode;
use common\utils\RSACrypt;
use common\utils\Encrypt;
use App\Models\DemoUser;

class UserService
{
    const STATUS_DISABLE = 0; // 账户停用
    const STATUS_ENABLE = 1;  // 账户启用
    //验证码前缀
    const PREFIX = 'auth_vcode:';

    const MEMBER_TOKEN = "member_token:";

    const DEFAULT_MAX_WITHDRAW_PWD_ERROR = 3;

    /**
     * 安全信息
     */
    public static function getSafetyInfo($id)
    {
        $info = SafeCenterService::getSafeCenter(["user_id" => $id]);
        if (empty($info)) {
            //新建安全中心
            SafeCenterService::addSafeCenter($id);
        }
        $data = UserService::getUserSafeInfo($id);
        if (!$data) {
            error_exit(SysCode::FAILED);
        }
        $config = SafeCenterService::SET_SAFETY;
        foreach ($config as $k => &$v) {
            if ($config[$k] && isset($data[$k]) && isset($data[$k . '_value'])) {
                if ($data[$k . '_value'] && $data[$k]) $v['value'] = $data[$k . '_value'];
            }
            if ($config[$k] && isset($data[$k])) {
                if ($data[$k]) $v['status'] = (string)$data[$k];
            }
        }
        return $config;
    }

    /**
     * 获取真实姓名
     */
    public static function getRealname($id)
    {
        $property = UserProperty::select('realname')->where(['user_id' => $id])->first();
        if ($property && $property['realname']) {
            return UserService::hideInfo('realname', $property['realname']);
        } else {
            return '';
        }
    }

    /**
     * 我的账户
     */
    public static function getWallet($id, $username)
    {
        $info = UserPropertyService::getFieldsValue($id, ['realname', 'last_login_time']);
        $re['username'] = $username;
        $re['realname'] = self::hideInfo('realname', $info['realname']);
        $re['last_login_time'] = $info['last_login_time'];
        //计算总余额
        $re['money'] = MoneyService::getTotalMoney($id);
        //用户各个游戏的有效投注总金额
        $partners = array_column(MoneyService::getPartnerList()->toArray(), 'name', 'partner_id');
        $re['bettingMoney'] = OrderService::getBettingMoneyByPartner($id, $partners);
        $re = amount_format_array($re, ['money', 'balance', 'bet_amount']);
        return $re;
    }

    /**
     * 获取用户id
     */
    public static function getUserId($params)
    {
        $user = Auth::user();
        if ($user) {
            $id = $user['id'];
        } else {
            $id = isset($params['id']) ? $params['id'] : null;
            if (!$id) {
                if (isset($params['email'])) {
                    $user = User::where("email", RSACrypt::rsaEncrypt($params['email']))->first();
                }
                if (isset($params['mobile'])) {
                    $user = User::where("mobile", RSACrypt::rsaEncrypt($params['mobile']))->first();
                }
                $id = $user ? $user['id'] : null;
            }
        }
        if (!$id) {
            error_exit(SysCode::INVALID_ARGUMENT);
        }
        return $id;
    }

    /**
     * 忘记密码
     */
    public static function forgetPwd($data)
    {
        $data = trim($data);
        $patternEmail = "/^([0-9A-Za-z\\-_\\.]+)@([0-9a-z]+\\.[a-z]{2,3}(\\.[a-z]{2})?)$/i";
        $patternMobile = "/\d/";
        if (preg_match($patternEmail, $data)) {
            $user = UserService::isExistEmail($data);
        } elseif (preg_match($patternMobile, $data)) {
            $user = UserService::isExistMobile($data);
        }
        if (empty($user)) {
            $user = User::where('username', $data)->first();
        }
        if ($user) {
            if (!is_array($user)) {
                $user = $user->toArray();
            }
            if (empty($user['email']) && empty($user['mobile'])) {
                error_exit(SysCode::USER_NOT_BIND_EMAIL_MOBILE);
            }
            $user = RSACrypt::rsaPatch($user);
            $user = self::hideInfos($user);
            return [
                'id' => $user['id'],
                'email' => $user['email'],
                'mobile' => $user['mobile']
            ];
        }
        error_exit(SysCode::USER_NOT_FOUND);
    }

    /**
     * 隐藏用户信息
     */
    public static function hideInfos($params)
    {
        $keys = ['email', 'mobile', 'idcard', 'realname'];
        if (is_array($params)) {
            foreach ($params as $k => $v) {
                if (is_array($v)) {
                    self::hideUserBaseInfo($v);
                } else {
                    if (in_array($k, $keys) && $params[$k]) {
                        $params[$k] = self::hideInfo($k, $v);
                    }
                }
            }
        }
        return $params;
    }

    public static function hideInfo($type, $data)
    {
        if(empty($data)){
            return '';
        }
        if ($type == 'email') {
            $email = explode('@', $data);
            if (!empty($email[0]) && !empty($email[1])) {
                $data = "****" . substr($email[0], -2) . '@' . $email[1];
            } else {
                $data = "****" . $data;
            }
        }
        if ($type == 'mobile' || $type == 'idcard') {
            $data = '****' . substr($data, -4);
        }
        if ($type == 'realname') {
            $data = substr($data, 0, 1) . '**' . substr($data, -1);
        }
        return $data;
    }

    /**
     * 用户绑定谷歌身份
     * @param $secret
     * @return array
     */
    public static function googleAuth($secret, $code, $id)
    {
        if (AuthService::verifyGoogleAuth($secret, $code)) {
            //保存谷歌密钥到用户表
            if (UserService::setGoogleSecret($secret, $id)) {
                //修改安全中心google_auth状态
                SafeCenter::where("user_id", $id)->update(["google_auth" => 1]);
                return true;
            }
        }
    }

    /**
     * 用户绑定谷歌身份密钥
     * @param $secret
     * @return array
     */
    public static function setGoogleSecret($secret, $id)
    {
        $update = User::where('id', $id)->update([
            "google_auth_key" => $secret
        ]);
        if (!$update) {
            error_exit(SysCode::USER_SAVE_GOOGLE_CODE_FAILED);
        }
        return true;
    }

    /**
     * 设置手机号码
     */
    public static function setMobile($id, $mobile, $code)
    {
        $mobile = trim($mobile);
        //是否设置过手机
        $user = UserService::getBaseinfo($id);
        if ($user['mobile']) {
            error_exit(SysCode::FAILED);
        }
        //检查手机是否已被注册
        if (self::isExistMobile($mobile)) {
            error_exit(SysCode::USER_MOBILE_EXIST);
        }
        if (SafeCenterService::validateMobileCode($id, $mobile, $code)) {
            //更新手机号码
            self::saveMobile($id, $mobile);
            return true;
        }
        error_exit(SysCode::FAILED);
    }


    /**
     * 修改邮箱
     */
    public static function updateEmail($id, $email, $code, $check)
    {
        $email = trim($email);
        //邮箱是否已被注册
        if (self::isExistEmail($email, $id)) {
            error_exit(SysCode::USER_EMAIL_EXIST);
        }
        if (SafeCenterService::validateEmailCode($id, $email, $code)) {
            //是否通过手机/登陆密码/邮箱验证
            SafeCenterService::checkUniqueCode($id, $check);
            self::saveEmail($id, $email);
            return true;
        }
        error_exit(SysCode::FAILED);
    }

    /**
     * 修改手机号码
     */
    public static function updateMobile($id, $mobile, $code, $check)
    {
        $mobile = trim($mobile);
        //检查手机是否已被注册
        if (self::isExistMobile($mobile, $id)) {
            error_exit(SysCode::USER_MOBILE_EXIST);
        }
        if (SafeCenterService::validateMobileCode($id, $mobile, $code)) {
            //是否通过手机/登陆密码/邮箱验证
            SafeCenterService::checkUniqueCode($id, $check);
            //更新手机号码
            self::saveMobile($id, $mobile);
            return true;
        }
        error_exit(SysCode::FAILED);
    }

    /**
     * 保存手机号码
     */
    public static function saveMobile($id, $mobile)
    {
        //更新手机
        $userUpdate = User::where('id', $id)->update(['mobile' => RSACrypt::rsaEncrypt($mobile)]);
        if (!$userUpdate) {
            error_exit(SysCode::FAILED);
        }
        //更新安全中心状态
        $safeUpdate = SafeCenter::where('user_id', $id)->update(['mobile' => 1]);
        if (!$safeUpdate) {
            error_exit(SysCode::FAILED);
        }
        return true;
    }

    public static function isExistMobile($mobile, $id = null)
    {
        $obj = User::where('mobile', RSACrypt::rsaEncrypt($mobile));
        if ($id) {
            $obj = $obj->where('id', '!=', $id);
        }
        if ($data = $obj->first()) {
            return $data->toArray();
        } else {
            return false;
        }
    }

    /**
     * 设置邮箱
     */
    public static function setEmail($id, $email, $code)
    {
        $email = trim($email);
        //检查用户是否设置过邮箱
        $user = UserService::getBaseinfo($id);
        if ($user['email']) {
            error_exit(SysCode::FAILED);
        }
        //检查邮箱是否已被注册
        if (self::isExistEmail($email)) {
            error_exit(SysCode::USER_EMAIL_EXIST);
        }
        if (SafeCenterService::validateEmailCode($id, $email, $code)) {
            self::saveEmail($id, $email);
            return true;
        }
        error_exit(SysCode::FAILED);
    }

    /**
     * 保存邮箱
     */
    public static function saveEmail($id, $email)
    {
        //更新邮箱
        $userUpdate = User::where('id', $id)->update(['email' => RSACrypt::rsaEncrypt($email)]);
        if (!$userUpdate) {
            error_exit(SysCode::FAILED);
        }
        //更新安全中心状态
        $safeUpdate = SafeCenter::where('user_id', $id)->update(['email' => 1]);
        if (!$safeUpdate) {
            error_exit(SysCode::FAILED);
        }
        return true;
    }

    public static function isExistEmail($email, $id = null)
    {
        $obj = User::where('email', RSACrypt::rsaEncrypt($email));
        if ($id) {
            $obj = $obj->where('id', '!=', $id);
        }
        if ($data = $obj->first()) {
            return $data->toArray();
        } else {
            return false;
        }
    }

    /**
     * 设置身份证号码
     */
    public static function setIdCard($params)
    {
        $user = Auth::user();
        if (!SafeCenterService::getSafeCenter(['user_id' => $user['id']])) {
            SafeCenterService::addSafeCenter($user['id']);
        }
        $property = UserProperty::where("user_id", $user['id'])->update([
            "idcard" => RSACrypt::rsaEncrypt($params['idcard']),
            "realname" => $params['realname']
        ]);
        if (!$property) error_exit(SysCode::FAILED);
        //更新安全中心状态
        $safeCenter = SafeCenter::where("user_id", $user['id'])->update(['id_card' => 1]);
        if (!$safeCenter) error_exit(SysCode::FAILED);
        return [
            'message' => __('message.safety_info_set_idcard', ['idcard' => substr($params['idcard'], -4)]),
            'realname' => mb_substr($params['realname'], 0, 1) . '*' . mb_substr($params['realname'], 2)
        ];
    }

    /**
     * 修改登陆密码
     */
    public static function modifyPassword($id, $params)
    {
        if (isset($params['old_pwd'])) {
            $check = UserService::verifyPassword($params['old_pwd'], $id);
        } elseif (isset($params['check'])) {
            //是否通过手机/登陆密码/邮箱验证
            $check = SafeCenterService::checkUniqueCode($id, $params['check']);
        }
        if ($check && isset($params['new_pwd']) && $params['new_pwd']) {
            if (UserService::updatePassword($params['new_pwd'], $id)) {
                return true;
            }
        }

    }

    /**
     * 修改登陆密码
     */
    public static function updatePassword($password, $id)
    {
        if (empty($password)) {
            return false;
        }
        $userInfo = DB::table('user')->select("salt")->where("id", $id)->first();
        $result = User::where('id', $id)->update([
            "password" => password_encrypt($password, $userInfo->salt)
        ]);
        return $result;
    }

    /**
     * 设置取款密码
     */
    public static function setWithdrawPassword($id, $params)
    {
        if (empty($params['pwd']) || empty($params['check'])) {
            error_exit(SysCode::FAILED);
        }
        SafeCenterService::checkUniqueCode($id, $params['check']);
        if (self::updateWithdrawPassword($id, $params['pwd'])) {
            return true;
        }
        return false;
    }

    /**
     * 修改取款密码
     */
    public static function modifyWithdrawPassword($id, $params)
    {
        if (empty($params['new_pwd'] || empty($params['old_pwd']))) {
            error_exit(SysCode::FAILED);
        }
        self::verifyWithdrawPassword($params['old_pwd'], $id);
        if (!UserService::updateWithdrawPassword($id, $params['new_pwd'])) {
            error_exit(SysCode::FAILED);
        }
        $attrs = [
            'user_id' => $id,
            'username' => $params['username'],
            'device' => isset($params['device']) ? $params['device'] : '',
            'type' => 6,
        ];
        UserLogService::create($attrs);
        return true;
    }

    public static function updateWithdrawPassword($id, $pwd)
    {
        // 为用户创建安全中心数据
        if (!($safeCenter = SafeCenterService::getSafeCenter(['user_id' => $id]))) {
            SafeCenterService::addSafeCenter($id);
        }
        $userInfo = DB::table('money')->select("salt")->where("user_id", $id)->first();
        $salt = empty($userInfo->salt) ? salt() : $userInfo->salt;
        $result = Money::where('user_id', $id)->update([
            "password" => password_encrypt($pwd, $salt),
            "salt" => $salt
        ]);
        if ($result) {
            // 修改安全中心状态 设置取款密码已设置
            SafeCenter::where('user_id', $id)->update(["withdraw_password" => 1]);
            return true;
        }
        error_exit(SysCode::FAILED);
    }

    /**
     * 校验取款密码
     */
    public static function verifyWithdrawPassword($password, $id = null)
    {
        if (empty($password)) {
            return false;
        }
        if (empty($id)) {
            $id = Auth::user()['id'];
        }
        $userInfo = DB::table('money')->select("password", "salt")->where("user_id", $id)->first();
        $password = password_encrypt($password, $userInfo->salt);
        if ($userInfo->password == $password) {
            return true;
        } else {
            error_exit(SysCode::USER_WITHDRAW_PASSWORD_ERROR);
        }
    }

    /**
     * 校验登陆密码
     */
    public static function verifyPassword($password, $id = null)
    {
        if (empty($password)) {
            return false;
        }
        if (empty($id)) {
            $id = Auth::user()['id'];
        }
        $userInfo = DB::table('user')->select("password", "salt")->where("id", $id)->first();
        $password = password_encrypt($password, $userInfo->salt);
        if ($userInfo->password == $password) {
            return true;
        } else {
            error_exit(SysCode::USER_PASSWORD_ERROR);
        }
    }

    public static function checkUserStatus($user)
    {
        if (empty($user)) {
            error_exit(SysCode::USER_NOT_LOGIN);
        }
        if ($user['status'] == self::STATUS_ENABLE) {
            return $user;
        } else {
            error_exit(SysCode::USER_STATE_ERROR);
        }
    }

    /**
     * 安全中心信息
     */
    public static function getUserSafeInfo($id)
    {
        if (empty($id)) return null;
        $user = UserService::getBaseinfo($id);
        $info = SafeCenterService::getSafeCenter(["user_id" => $id]);
        //手机
        if ($info['mobile'] == 1) $info['mobile_value'] = __('message.safety_info_mobile', ['mobile' => substr($user['mobile'], -4)]);
        //google验证
        if ($info['google_auth'] == 1) $info['google_auth_value'] = __('message.safety_info_google_auth');
        //邮箱
        if ($info['email'] == 1) {
            $email = explode('@', $user['email']);
            if (!empty($email[0]) && !empty($email[1])) {
                $info['email_value'] = __('message.safety_info_email', ['email' => substr($email[0], -2) . '@' . $email[1]]);
            } else {
                $info['email_value'] = __('message.safety_info_email', ['email' => $user['email']]);
            }
        }
        //身份证
        if ($info['id_card'] == 1) {
            $model = UserProperty::where(['user_id' => $id])->first();
            if ($model) {
                $info['id_card_value'] = __('message.safety_info_idcard', ['idcard' => substr(RSACrypt::rsaDecrypt($model['idcard']), -4)]);
            } else {
                $info['id_card_value'] = '';
            }
        }
        return $info;
    }

    // 获取用户信息
    public static function getBaseinfo($id)
    {
        $user = User::find($id);
        if (!$user) {
            return [];
        }
        $user = $user->toArray();
        return RSACrypt::rsaPatch($user);
    }

    public static function login($credentials)
    {
        // 没有用户名，查agent,demo
        if (!isset($credentials['username'])) {
            if (isset($credentials['agent'])) {
                // agent登录
                Auth::setDefaultDriver('agent');
                $credentials['username'] = $credentials['agent'];
            } elseif (isset($credentials['demo'])) {
                // 试玩登录
                Auth::setDefaultDriver('demo');
                $credentials['username'] = $credentials['demo'];
            }
        }
        // 参数错误
        if (!isset($credentials['username']) || !isset($credentials['password'])) {
            error_exit(SysCode::INVALID_ARGUMENT);
        }
        $token = Auth::attempt(['username' => $credentials['username'], 'password' => $credentials['password']]);
        if (!$token) {
            return error_exit(SysCode::USER_AUTH_NOT_MATCH);
        }
        return self::userFormat(Auth::user(), $token);
    }

    // 免密登录
    public static function loginByCode($credentials, $code)
    {
        if (isset($credentials['mobile'])) {
            $user = User::where(['mobile' => RSACrypt::rsaEncrypt($credentials['mobile'])])->first();
            $key = $credentials['mobile'];
        } elseif (isset($credentials['email'])) {
            $user = User::where(['email' => RSACrypt::rsaEncrypt($credentials['email'])])->first();
            $key = $credentials['email'];
        } else {
            return error_exit(SysCode::INVALID_ARGUMENT);
        }
        if (empty($user)) {
            return error_exit(SysCode::USER_NOT_FOUND);
        }
        if (!SafeCenterService::validateCode($user['id'], $key, $code)) {
            return error_exit(SysCode::INVALID_CODE);
        }
        $token = Auth::fromUser($user);
        return UserService::userFormat($user, $token);
    }

    public static function userFormat($user, $token)
    {
        $redis = Redis::connection();
        $redis->set(self::MEMBER_TOKEN . $user->getJWTIdentifier(), $token, 'EX', config('jwt.ttl') * 60);
        $attr = $user->toArray();
        return [
            'user' => RSACrypt::rsaPatch($attr),
            'token' => $token,
        ];
    }

    public static function logout()
    {
        $user = Auth::user();
        if (!$user) {
            return error_exit(SysCode::USER_TOKEN_EXPIRE);
        }
        Auth::logout();
        $redis = Redis::connection();
        $redis->del(self::MEMBER_TOKEN . $user->getJWTIdentifier());
    }

    public static function register($attrs)
    {
        // 查看用户是否已注册
        if (User::where('username', $attrs['username'])->first()) {
            return error_exit(SysCode::USER_EXIST, ['username' => $attrs['username']]);
        }
        DB::beginTransaction();
        // 加密
        $attrs = RSACrypt::rsaPatch($attrs, Encrypt::ENCRYPT);
        try {
            // 新建用户
            $user = new User($attrs);
            $user->salt = salt();
            $user->password = password_encrypt($user->password, $user->salt);
            $user->register_ip = Request::getClientIp();

            if (!$user->save()) {
                Log::error('User Save Error.', $attrs);
                DB::rollBack();
                return false;
            }

            // 新建资料
            $property = new UserProperty($attrs);
            $property->user_id = $user->id;

            if (!$property->save()) {
                Log::error('UserProperty Save Error.', $attrs);
                DB::rollBack();
                return false;
            }

            // 新建主钱包，子钱包在资金变动的时候生成（同步，转账等）
            $money = new Money();
            $money->user_id = $user->id;
            if (isset($attrs['withdraw_password'])) {
                $money->salt = salt();
                $money->password = password_encrypt($attrs['withdraw_password'], $money->salt);
            }
            if (!$money->save()) {
                Log::error('Money Save Error.', $attrs);
                DB::rollBack();
                return false;
            }

            // 新建安全中心
            $safeCenter = new SafeCenter();
            $safeCenter->user_id = $user->id;
            $safeCenter->withdraw_password = isset($attrs['withdraw_password']);
            $safeCenter->mobile = isset($attrs['mobile']);
            $safeCenter->email = isset($attrs['email']);
            if (!$safeCenter->save()) {
                Log::error('SafeCenter Save Error.', $attrs);
                DB::rollBack();
                return false;
            }

            DB::commit();
            return true;
        } catch (\Exception $e) {
            Log::error('User register Error.', $attrs);
            DB::rollBack();
            return false;
        }
        return true;
    }

    /**
     * 获取验证码
     *
     * @param int $length
     * @return array
     */
    public static function getVcode($length = 4)
    {
        $vc = new ValidateCode();
        $vc->create($length);

        $code = $vc->getCode();
        $image = $vc->getBase64();
        $hash = md5(sha1(uniqid(self::PREFIX)));

        $redis = Redis::connection();
        $redis->set(self::PREFIX . $hash, $code, 'EX', 180);

        return ['hash' => $hash, 'img' => $image];
    }

    /**
     * 验证验证码
     *
     * @param string $hash
     * @param int $code
     * @return boolean
     */
    public static function validateVcode($hash = '', $code = 0)
    {
        $redis = Redis::connection();
        $vcode = $redis->get(self::PREFIX . $hash);
        if (!$vcode) {
            return false;
        }
        $redis->del(self::PREFIX . $hash);

        return $code == $vcode;
    }

    /**
     * 验证Token
     *
     * @param int $id
     * @param string $token
     * @return boolean
     */
    public static function validateToken($id, $token)
    {
        $redis = Redis::connection();
        $t = $redis->get(self::MEMBER_TOKEN . $id);

        return $token == $t;
    }

    public static function formatOrders($data)
    {
        if (empty($data)) return $data;
        foreach ($data as $k => $val) {
            if (isset($data['type']) && $data['type'] == 4) {
                $source = json_decode($val['source'], true);
                if (isset($source['detail']) && !empty($source['detail'])) {
                    foreach ($source['detail'] as $key => $value) {
                        $gamename = $value['game_name'];
                        if ($value['part_name'] == '[a]') {
                            $value['part_name'] = $value['team1_name'];
                        }
                        if ($value['part_name'] == '[b]') {
                            $value['part_name'] = $value['team2_name'];
                        }
                        $part_arr[] = $value['part_name'] . ' ' . amount_format($value['part_odds']);
                    }
                    $data[$k]['name'] = implode(',', $part_arr);
                    $data[$k]['game_name'] = $gamename;
                } else {
                    if ($source['part_name'] == '[a]') {
                        $source['part_name'] = $source['team1_name'];
                    }
                    if ($source['part_name'] == '[b]') {
                        $source['part_name'] = $source['team2_name'];
                    }
                    $data[$k]['name'] = $source['part_name'] . ' ' . amount_format($source['part_odds']);
                }
            } else {
                $data[$k]['name'] = $val['partner_name'];
            }
            $data[$k]['name'] = $data[$k]['name'] == 'BI' ? 'HC电竞' : $data[$k]['name'];
            $data[$k]['time'] = $val['bet_time'];
            $data[$k]['order_number'] = $val['order_number'];
            if ($val['state'] == 2) {
                $data[$k]['validbet'] = $val['validbet'];
            } else {
                $data[$k]['validbet'] = 0;
            }
            $data[$k]['bet_amount'] = $val['bet_amount'];//投注金额
            $data[$k]['profit'] = $val['profit'];//输赢
            $data[$k]['prize'] = $val['prize'];//派奖金额
            $data[$k]['bet_content'] = $val['bet_content'];//投注内容与结果等内容拼接
            if ($val['state'] == 2) {
                if ($val['prize'] > 0) {
                    $data[$k]['state'] = 1;    //中奖
                } elseif ($val['prize'] == 0 && $val['profit'] < 0) {
                    $data[$k]['state'] = 2;   //未中奖
                }
            }
            unset($data[$k]['source']);
        }
        $data = amount_format_array($data, ['validbet', 'bet_amount', 'profit', 'prize']);
        return $data;
    }

    public static function countSubTotal($orders)
    {
        $subTotalMoney = ['bet_amount' => 0, 'validbet' => 0, 'send_prize' => 0, 'lose_earn' => 0];
        //小计
        foreach ($orders as $k => $order) {
            //注单状态:0=等待；1=接受；2=结算；3=取消；4=拒绝
            if ($order['state'] == 2) {
                $subTotalMoney['send_prize'] += $order['prize'];
                $subTotalMoney['lose_earn'] += $order['profit'];
            }
            $subTotalMoney['bet_amount'] += $order['bet_amount'];
            $subTotalMoney['validbet'] += $order['validbet'];
        }
        $subTotalMoney = amount_format_array($subTotalMoney);
        return $subTotalMoney;
    }
}
